package cyy.example.com.facotry.net;

import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.example.com.common.utils.JsonUtil;
import com.example.com.common.utils.LogUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cyy.example.com.facotry.BuildConfig;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.share.SPEngine;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Network {
  private static Network instance;
  private Retrofit retrofit;

  static {
    instance = new Network();
  }

  private Network() {
  }

  /**
   * 构建一个Retrofit
   *
   * @return
   */
  public static Retrofit getRetrofit() {
    if (instance.retrofit != null)
      return instance.retrofit;

    OkHttpClient client = createHttpClient();
    Retrofit.Builder builder = new Retrofit.Builder();

    // 设置电脑链接
    instance.retrofit = builder.baseUrl(CommonConstants.API_URL_PREFIX)
      // 设置client
      .client(client)
      // 设置Json解析器
      .addConverterFactory(GsonConverterFactory.create(Factory.getGson()))
//                .addConverterFactory(StringConverterFactory.create())
      .build();
    return instance.retrofit;
  }

  /**
   * 创建okhhtp实例
   *
   * @return
   */
  @NonNull
  private static OkHttpClient createHttpClient() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    if (BuildConfig.DEBUG) {
      logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    }
    else {
      logging.setLevel(HttpLoggingInterceptor.Level.NONE);
    }

    // 得到一个OK Client 
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
//                 给所有的请求添加一个拦截器
//      .addInterceptor(logging)
      .addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
          Request request = chain.request();
          Request.Builder builder = request.newBuilder();
          SPEngine spEngine = SPEngine.getSPEngine();
          String token = spEngine.getUserInfo().getSetMobileToken();
          if (!TextUtils.isEmpty(token)) {
            // 添加公用的头

            try {
              builder.addHeader("Authorization", token);
            }
            catch (Exception e) {
              e.printStackTrace();
            }
          }
          builder.addHeader("device", "mobile");
//                        builder.addHeader("Content-Type", "text/html");
//                        builder.addHeader("charset", "utf-8");
          //创建新的request
          Request newRequest = builder.build();
          //-------请求打印日志
          Response response = chain.proceed(newRequest);
          return response;
        }
      })
      .addNetworkInterceptor(httpLoggingInterceptor())
      //设置超时
      .connectTimeout(30, TimeUnit.SECONDS)
      .readTimeout(30, TimeUnit.SECONDS)
      .writeTimeout(30, TimeUnit.SECONDS);
    return builder.build();
  }

  private static HttpLoggingInterceptor httpLoggingInterceptor() {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
      final StringBuilder mMessage = new StringBuilder();

      @Override
      public void log(String message) {
        if (BuildConfig.DEBUG) {
//                    Log.e("Http", "OkHttp====message " + message);
//                    Logger.json(message);

          // 请求或者响应开始
          if (message.startsWith("--> POST")) {
            mMessage.setLength(0);
          }
          // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
                    if ((message.startsWith("{") && message.endsWith("}"))
                      || (message.startsWith("[") && message.endsWith("]"))) {
                        message = JsonUtil.getInstance().formatJson(JsonUtil.getInstance().decodeUnicode(message));
                    }
          mMessage.append(message.concat("\n"));
          // 响应结束，打印整条日志
          if (message.startsWith("<-- END HTTP")) {
            LogUtil.e(mMessage.toString());
          }
        }
      }
    });
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return interceptor;
  }

  /**
   * 重置retrofit
   * 当需要切换请求域名地址时，调用重置
   */
  public static void restRetrofit() {
    if (instance.retrofit != null) {
      String s = instance.retrofit.baseUrl().toString();
      if (!CommonConstants.API_URL_PREFIX.equals(s)) {
        instance.retrofit = null;
      }
    }
  }

  /**
   * 返回一个请求代理
   *
   * @return RemoteService
   */
  public static RemoteService remote() {
    return Network.getRetrofit().create(RemoteService.class);
  }

}
